package cfca.trustsign.demo.op;

import cfca.sadk.algorithm.common.PKIException;
import cfca.sadk.util.Base64;
import cfca.trustsign.common.util.CommonUtil;
import cfca.trustsign.common.vo.cs.*;
import cfca.trustsign.common.vo.request.tx3.*;
import cfca.trustsign.demo.connector.HttpConnector;
import cfca.trustsign.demo.constant.Request;
import cfca.trustsign.demo.converter.JsonObjectMapper;
import cfca.trustsign.demo.util.SecurityUtil;
import cfca.trustsign.demo.util.TimeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

public class CfcaOp {

    @Autowired
    @Lazy
    static RedisUtil redisUtil;

    //判断是否为pdf
    private static boolean isPdf(byte[] pdfBytes) {
        return pdfBytes.length > 5 && pdfBytes[0] == 0x25 && pdfBytes[1] == 0x50 && pdfBytes[2] == 0x44 && pdfBytes[3] == 0x46 && pdfBytes[4] == 0x2D;
    }

    public static<T extends Tx3ReqVO> String send(String txCode, T TxReqVO){
        HttpConnector httpConnector = new HttpConnector();
        httpConnector.init();

        HeadVO head = new HeadVO();
        head.setTxTime(TimeUtil.getCurrentTime(TimeUtil.FORMAT_14));
        TxReqVO.setHead(head);

        JsonObjectMapper jsonObjectMapper = new JsonObjectMapper();
        String req = jsonObjectMapper.writeValueAsString(TxReqVO);
        System.out.println("req:" + req);


        String signature = null;
        try {
            signature = SecurityUtil.p7SignMessageDetach(HttpConnector.JKS_PATH, HttpConnector.JKS_PWD, HttpConnector.ALIAS, req);
        } catch (PKIException e) {
            throw new JeecgBootException("请求失败");
        }
        String res = httpConnector.post("platId/" + Request.PLAT_ID + "/txCode/" + txCode + "/transaction", req, signature);
        System.out.println("res:" + res);
        return res;
    }
    public static<T extends Tx3ReqVO> String sendFile(String txCode, T TxReqVO,File file){
        HttpConnector httpConnector = new HttpConnector();
        httpConnector.init();

        HeadVO head = new HeadVO();
        head.setTxTime(TimeUtil.getCurrentTime(TimeUtil.FORMAT_14));
        TxReqVO.setHead(head);

        JsonObjectMapper jsonObjectMapper = new JsonObjectMapper();
        String req = jsonObjectMapper.writeValueAsString(TxReqVO);
        System.out.println("req:" + req);


        String signature = null;
        try {
            signature = SecurityUtil.p7SignMessageDetach(HttpConnector.JKS_PATH, HttpConnector.JKS_PWD, HttpConnector.ALIAS, req);
        } catch (PKIException e) {
            throw new JeecgBootException("请求失败");
        }
        String res = httpConnector.post("platId/" + Request.PLAT_ID + "/txCode/" + txCode + "/transaction", req, signature,file);
        System.out.println("res:" + res);
        return res;
    }
    public static InputStream downloadContract(String contractNo){
        HttpConnector httpConnector = new HttpConnector();
        httpConnector.init();
        byte[] fileBtye = httpConnector.getFile("platId/" + Request.PLAT_ID + "/contractNo/" + contractNo + "/downloading");
        if (CommonUtil.isEmpty(fileBtye)) {
            throw new JeecgBootException("文件更新失败");
        }
        InputStream sbs = new ByteArrayInputStream(fileBtye);
        return sbs;
    }

    public static byte[] downloadByteContract(String contractNo){
        HttpConnector httpConnector = new HttpConnector();
        httpConnector.init();
        byte[] fileByte = httpConnector.getFile("platId/" + Request.PLAT_ID + "/contractNo/" + contractNo + "/downloading");
        if (CommonUtil.isEmpty(fileByte)) {
            throw new JeecgBootException("文件更新失败");
        }
        return fileByte;
    }
    //查询用户信息3008
    public static String getCus(String username,String idenTypeCode,String indentNo){
        Tx3008ReqVO tx3008ReqVO = new Tx3008ReqVO();
        UserInfoVO userInfo = new UserInfoVO();
        userInfo.setUserName(username);
        userInfo.setIdentTypeCode(idenTypeCode);
        userInfo.setIdentNo(indentNo);
        tx3008ReqVO.setUserInfo(userInfo);
        String txCode = "3008";
        return send(txCode,tx3008ReqVO);
    }

    //个人开户3001
    public static String ctreatePerson(PersonVO person){
        Tx3001ReqVO tx3001ReqVO = new Tx3001ReqVO();
        tx3001ReqVO.setPerson(person);
        String txCode = "3001";
        return send(txCode,tx3001ReqVO);
    }

    //企业开户3002
    public static String ctreateEnterprise(EnterpriseVO enterprise,EnterpriseTransactorVO enterpriseTransactor){
        Tx3002ReqVO tx3002ReqVO = new Tx3002ReqVO();
        tx3002ReqVO.setEnterprise(enterprise);
        tx3002ReqVO.setEnterpriseTransactor(enterpriseTransactor);
        String txCode = "3002";
        return send(txCode,tx3002ReqVO);
    }

    //增加印章3011,url是本地图片地址
    public static String addSeal(SealAddVO sealAddVO,String url){

        Tx3011ReqVO tx3011ReqVO = new Tx3011ReqVO();
        tx3011ReqVO.setSealAdd(sealAddVO);

        SealVO sealVO = new SealVO();
        try {
            sealVO.setImageData(Base64.toBase64String(Files.readAllBytes(Paths.get(url))));
        } catch (IOException e) {
            throw new JeecgBootException("文件读取失败");
        }
        sealAddVO.setSeal(sealVO);

        String txCode = "3011";
        return send(txCode,tx3011ReqVO);
    }

    /**
     * 发送验证码代理签约，目前仅D227A8F0769D096FE05311016B0AB8D8用户生效
     *
     * **/
    public static String proxySignSend(ProxySignVO proxySignVO){
        Tx3101ReqVO tx3101ReqVO = new Tx3101ReqVO();
//        proxySignVO.setUserId("D227A8F0769D096FE05311016B0AB8D8");
        tx3101ReqVO.setProxySign(proxySignVO);
        String txCode = "3101";
        return send(txCode,tx3101ReqVO);
    }

    public static String proxySignReceive(ProxySignVO proxySignVO){
        Tx3102ReqVO tx3102ReqVO = new Tx3102ReqVO();
        tx3102ReqVO.setProxySign(proxySignVO);
        String txCode = "3102";
        return send(txCode,tx3102ReqVO);
    }

    /**
     * 创建合同3201
     * */
    public static String createContract(CreateContractVO createContract){

        Tx3201ReqVO tx3201ReqVO = new Tx3201ReqVO();
        tx3201ReqVO.setCreateContract(createContract);
        String txCode = "3201";
        return send(txCode,tx3201ReqVO);
    }

    //上传合同签署3203
    public static String uploadContract(UploadContractVO uploadContract,File file){
        Tx3203ReqVO tx3203ReqVO = new Tx3203ReqVO();
        tx3203ReqVO.setUploadContract(uploadContract);
        String txCode = "3203";
        return sendFile(txCode,tx3203ReqVO,file);
    }

    //签署合同3206
    public static String signContract(SignContractVO signContract){
        Tx3206ReqVO tx3206ReqVO = new Tx3206ReqVO();
        tx3206ReqVO.setSignContract(signContract);
        String txCode = "3206";
        return send(txCode,tx3206ReqVO);
    }
    //根据关键字签署合同3207
    public static String signContractByKeyword(String contractNo,String contract){
        Tx3207ReqVO tx3207ReqVO = new Tx3207ReqVO();
        SignContractByKeywordVO signContractByKeyword = new SignContractByKeywordVO();
        signContractByKeyword.setContractNo(contractNo);
        //从redis中获取签名用户以及签名地点信息
        JSONObject parseObject = JSONObject.parseObject(contract);
        UploadContractVO contractVO = JSON.toJavaObject(parseObject, UploadContractVO.class);
        signContractByKeyword.setSignKeyword(contractVO.getSignKeyword());
        signContractByKeyword.setSignInfo(contractVO.getSignInfos()[0]);
        tx3207ReqVO.setSignContractByKeyword(signContractByKeyword);
        String txCode = "3207";
        return send(txCode,tx3207ReqVO);
    }


    public static void main(String[] args) throws PKIException, IOException {
        HttpConnector httpConnector = new HttpConnector();
        httpConnector.init();

        Tx3011ReqVO tx3011ReqVO = new Tx3011ReqVO();
        HeadVO head = new HeadVO();
        head.setTxTime(TimeUtil.getCurrentTime(TimeUtil.FORMAT_14));

        SealAddVO sealAddVO = new SealAddVO();
        sealAddVO.setUserId("F95ED2BF390B4DCF8AE175A97112EDDD");

        SealVO sealVO = new SealVO();

        sealVO.setImageData(Base64.toBase64String(Files.readAllBytes(Paths.get("./image/王五.png"))));
        sealAddVO.setSeal(sealVO);

        tx3011ReqVO.setHead(head);
        tx3011ReqVO.setSealAdd(sealAddVO);

        JsonObjectMapper jsonObjectMapper = new JsonObjectMapper();
        String req = jsonObjectMapper.writeValueAsString(tx3011ReqVO);
        System.out.println("req:" + req);

        String txCode = "3011";
        String signature = SecurityUtil.p7SignMessageDetach(HttpConnector.JKS_PATH, HttpConnector.JKS_PWD, HttpConnector.ALIAS, req);
        String res = httpConnector.post("platId/" + Request.PLAT_ID + "/txCode/" + txCode + "/transaction", req, signature);
        System.out.println("res:" + res);
    }
}
